import store from '@/store'
import { uuid } from 'vue-uuid';
import router from '@/router';
import { mapMutations } from 'vuex';
import CommonData from "@/common/data"
//解析失败
function tokenFaile(){
    store.dispatch('Login/loginOut')
    router.push({path:'/home'}, () => {})
    AddInform({content:'Token失效,请重新登录',type:'danger'})
    store.commit('Login/LOGINSTATEON')
}
// 退出登录
function Logout(uid){
    store.dispatch('Login/loginOut',uid)
    router.push({path:'/home'}, () => {})
}
//返回上一层
function Back(deleted){
    if (window.history.length <= 2) {
        router.push({path:'/home'})
        return false
    } 
    router.back()
}
//去个人主页
function ToPersonal(personaluid){
     let uid=localStorage.getItem('User')?JSON.parse(localStorage.getItem('User'))?.uid : 0
     if(uid != personaluid)
     {
        let routeUrl= router.resolve({path:'/personal', query: { uid: personaluid } }, () => {})
        window.open(routeUrl.href, "_blank");
     }
     else router.push({path:'/personal', query: { uid: personaluid } }, () => {})
}
//去文章详情
function ToArticleDeatil(articleid){
    router.push({path:'/articleDetail', query: { articleid} }, () => {})
}
//登录框展现
function toLogin(){
    AddInform({content:'请先登录',type:'danger'})
    store.commit('Login/LOGINSTATEON')
}


 function getContent(value,style){
	let content=value.split('\n')
	let newcontent=""
	content.forEach((item)=>{
		if(item!="")
		newcontent+=`<p ${style}>${item}</P>`
	})
	return newcontent
}

function resolve(item){
    let state=0
    let res = ''
    let now = ''
    let url = CommonData.emoUrl
    for (let index = 0; index < item.length; index++) {
        if(item[index]=='[') {
            state=1
            now += item[index]
        }
        else if( state==1 && item[index]==']') {
           state=0
           now+=item[index]
           let resData = CommonData.emoData.find(item => item.value == now)
           if(resData) res += `<img  src="${url + resData.src}"  style="width:25px;height:25px"/>`
           now=''
        }
        else if(state == 0){
           res += item[index]
        }       
        else if(state == 1){
         now += item[index]
       }         
    }
    res += now
    return res
 }
 function initContent(value){
   let content=value.split('\n')
     let newcontent=""
     content.forEach((item)=>{
         if(item!="")
         {
       let res =resolve(item)
       newcontent+=`<div style="width:100%;justify-content:flex-start" class="flex">${res}</div>`
     }
     })
     return newcontent
 }
function changePosition(potisition){
    let max=document.documentElement.scrollTop + document.documentElement.scrollHeight
     if(potisition < 0) potisition=0
     else if(potisition >= max)
     potisition=max
     return potisition
}

// 页面滚动
function Move(from,to,time){
    store.commit('Tool/SETNAVIGATION',[false,false])
    store.commit('Tool/SETNAVIGATIONFLAG',false)

             //防止上滚的时候不让导航条出现
    from=changePosition(from)
    to = changePosition(to)
    let type = from >= to ? 'up' : 'down'
    let count = time /10 
    let v = parseInt(Math.abs(from - to) / count) 
    v= v<=5 ? 5:v
    if(type=='up'){
        const timer = setInterval(() => {    
                document.body.scrollTop = document.documentElement.scrollTop = from -= v
                if(from <= to)
                {
                    clearInterval(timer)
                    
                    let timer2= setTimeout(() => {
                        store.commit('Tool/SETNAVIGATIONFLAG',true)
                        clearTimeout(timer2)
                    }, 200);
                    
                }
        }, 10)
       return
    }

    const timer = setInterval(() => {    
           document.body.scrollTop = document.documentElement.scrollTop = from += v
            if(from >= to)
            {
                clearInterval(timer)
                let timer2= setTimeout(() => {
                    store.commit('Tool/SETNAVIGATIONFLAG',true)
                    clearTimeout(timer2)
                }, 200);
            }
      }, 10)
    
}
//回到顶部
function toTop(time){
    let top = document.documentElement.scrollTop || document.body.scrollTop
    let count = time /10 
    let v = parseInt(top / count)
        const timer = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= v
            if (top <= 0) {
                clearInterval(timer)
            }
     }, 10)
 }
//分组
 function Devision(arr,lenth) {
    var newArr = [];
    let index=0;
       for (var i = 0; i < arr.length; i += lenth) {
          let data={}
          data.data=arr.slice(i, i + lenth)
          data.id=index
          data.formState=0
          index+=1
          newArr.push(data);
       }
       return newArr
}

//左侧通知
function setColor(value,color,backColor,icon){
     value.color= value.color||color || null
     value.backColor= value.backColor||backColor||null
     value.icon= value.icon||icon||'el-icon-message'
     return value
}
function AddInform(value){
    let id=uuid.v1()
    value.id=id
    if(value.type=='success')  value=setColor(value,'#67C23A','#F0F9EB','el-icon-circle-check') 
    else if(value.type=='info') value=setColor(value,'#909399','#EDF2FC','el-icon-warning-outline')  
    else if(value.type=='warning')value=setColor(value,'#E6A23C','#FDF6EC') 
    else  if(value.type=='danger')value=setColor(value,'#F56C6C','#FEF0F0')
    else  if(value.type=='Day')value=setColor(value,null,'#FEA500','fa-sun')
    else  if(value.type=='Night')value=setColor(value,null,'#03e9f4','fa-moon')
    else  if(value.type=='Dark')value=setColor(value,null,'#5C5893','star-and-crescent')

    let data={duration: 3,icon:'el-icon-message',isShow:false}
    let newData={...data,...value}
    
    store.commit('Tool/INFOEMADD',newData)
    setTimeout(() => {
        newData.isShow=true
     }, 100);
}
//得到具体时间
function getCurrentDetailTime(){
    var date=new Date();
    let yy=date.getFullYear()
    let mm=date.getMonth()+1
    let dd=date.getDate()
    let hh=date.getHours()
    let minute=date.getMinutes()
    let second=date.getSeconds()
    let time=yy+'-'+mm+'-'+dd+' '+hh+':'+minute+':'+second
    return time
}
//比较时间
function CompareTime(oldtime,newtime) {
    if(oldtime ==null) return true
    if(newtime ==null) return false
    var date1 = new Date(oldtime);
    var time1 = date1.getTime();
    var date2 = new Date(newtime);
    var time2 = date2.getTime();
    return time1<time2
}
//超过时间
function OverTime(oldtime,newtime,time) {
    if(oldtime ==null) return true
    if(newtime ==null) return false
    var date1 = new Date(oldtime);
    var time1 = date1.getTime();
    var date2 = new Date(newtime);
    var time2 = date2.getTime();
    return time2 -time1 >= time
}

//过滤敏感信息
function filterSensitiveInfo(info,symbol='**'){
    if(! Number.isInteger(info))
    info=info.replace(CommonData.sensitiveReg,symbol);//找到匹配的替换成*
    return info
 }
export default {		
	Logout,
    toLogin,
    getContent,
    toTop,
    Move,
    Devision,
    AddInform,
    Back,
    ToPersonal,
    ToArticleDeatil,
    initContent,
    getCurrentDetailTime,
    CompareTime,
    OverTime,
    filterSensitiveInfo,
    tokenFaile
}
